package cn.edu.nju.ws.sview.group;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import cn.edu.nju.ws.sview.cache.MessageCache;
import cn.edu.nju.ws.sview.database.DBConnectionFactory;
import cn.edu.nju.ws.sview.views.Group;
import cn.edu.nju.ws.sview.views.User;

import com.hp.hpl.jena.sparql.lib.org.json.JSONException;

public class GroupCreateValidate extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String json = request.getParameter("gcreate");
		//System.out.println("validating..."+json);
		String result = null;
		if(json != null){
			URLDecoder coder = new URLDecoder();
			String data = coder.decode(json, "utf8");
			JSONObject regtJSON = (JSONObject) JSONValue.parse(data);
			try {
				String action = (String) regtJSON.get("action");
				String value = (String) regtJSON.get("value");
				if(action.contentEquals("checkExistGName")){
					Connection conn = DBConnectionFactory.getConnection();
					PreparedStatement pstmt = conn.prepareStatement("select id from edit_group where name=?");
					pstmt.setString(1, value);
					ResultSet rs = pstmt.executeQuery();
					if(rs.next()){
						result = "exist";
					}else{
						result = "notexist";
					}
					rs.close();
					pstmt.close();
					conn.close();
				}else if(action.contentEquals("searchMember")){
					Connection conn = DBConnectionFactory.getConnection();
					PreparedStatement pstmt = conn.prepareStatement("select id,name,email from user where name=?");
					pstmt.setString(1, value);
					ResultSet rs = pstmt.executeQuery();
					result = "";
					while(rs.next()){
						result += rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3);
					}
					if(result.length() == 0){
						result = null;
					}
					rs.close();
					pstmt.close();
					conn.close();
				}else if(action.contentEquals("addAll")){
					if(value.length()>0){
						int gid = Integer.valueOf((String)regtJSON.get("gid"));
						String gname = Group.getGroupNameById(gid);
//						System.out.println("gid:"+gid+"\tgname:"+gname);
						String[] uids = value.split(",");
						Timestamp time = new java.sql.Timestamp(new Date().getTime());
						String title = "Invitation From Group '"+gname+"'";
						String content = "Dear friend,<br/>I'm glad to invite you to join our <a id='gname' href='javascript:void(0)'>"+gname+"</a> group. You can accept my invitation by click <a class='accept' href='javascript:void(0)'>accept</a>, or reject by click <a class='reject' href='javascript:void(0)'>reject</a>.";
						int uid = Integer.valueOf(User.getUserIdByName((String)request.getSession().getAttribute("user")));
						Connection conn = DBConnectionFactory.getConnection();
						/*PreparedStatement pstmt = conn.prepareStatement("insert ignore into group_member(gid,uid,time) values(?,?,?)");
						for(int i=0; i<uids.length; i++){
							if(uids[i].length()>0){
								pstmt.setInt(1, gid);
								pstmt.setInt(2, Integer.valueOf(uids[i]));
								pstmt.setTimestamp(3, time);
								pstmt.addBatch();
							}
						}*/
						PreparedStatement pstmt = conn.prepareStatement("insert ignore into msg(title,time,sender_id,receiver_id,content) values(?,?,?,?,?)");
						PreparedStatement psys = conn.prepareStatement("insert ignore into msg(title,time,sender_id,receiver_id,content) values(?,?,?,?,?)");
						ArrayList<String> names = new ArrayList<String>();
						for(int i=0; i<uids.length; i++){
							if(uids[i].length()>0){
								pstmt.setString(1, title);
								pstmt.setTimestamp(2, time);
								pstmt.setInt(3, uid);
								pstmt.setInt(4, Integer.valueOf(uids[i]));
								pstmt.setString(5, content);
//								pstmt.addBatch();
								pstmt.execute();
								
								names.add(User.getUserNameById(Integer.valueOf(uids[i])));
								MessageCache.getInstance().updateMessages(Integer.valueOf(uids[i]));//=============
							}
						}
//						pstmt.executeBatch();
//						pstmt.clearBatch();
						if(names.size()>0){
							psys.setString(1, "Invitation Sended Successfully");
							psys.setTimestamp(2, time);
							psys.setInt(3, 0);//SystemId=0
							psys.setInt(4, uid);
							psys.setString(5, "&nbsp;&nbsp;&nbsp;&nbsp;Dear user,<br/>&nbsp;&nbsp;&nbsp;&nbsp;Your invitation" +
									" for group <b>"+gname+"</b> to user(s) <b>"+names.toString().replace("[", "").replace("]", "")+"</b> have been send to their message box successfully. Please wait patiently for their feed back.");
							psys.executeUpdate();
						}
						psys.close();
						pstmt.close();
						conn.close();
						result="Invite messages have send to these users,\nplease wait for their acceptence";
						MessageCache.getInstance().updateMessages(uid);
					}
				}else if(action.contentEquals("join")){
						if(value.length()>0){
							int gid = Integer.valueOf((String)regtJSON.get("gid"));
							String gname = Group.getGroupNameById(gid);
							String client_uid = value;
							String user_name=User.getUserNameById(Integer.parseInt(client_uid));
							Timestamp time = new java.sql.Timestamp(new Date().getTime());
							String title = "Apply for Group '"+gname+"'";
							String content = "Dear administrator,<br/>User <b>"+user_name+"</b> want to join your <a id='gname' href='javascript:void(0)'>"+gname+"</a> group. You can accept the appliment by click <a class='acceptApply' href='javascript:void(0)'>accept</a>, or reject by click <a class='rejectApply' href='javascript:void(0)'>reject</a>.";
							int admin_uid = Group.getGroupIdByName(gname);
							Connection conn = DBConnectionFactory.getConnection();
							/*PreparedStatement pstmt = conn.prepareStatement("insert ignore into group_member(gid,uid,time) values(?,?,?)");
							for(int i=0; i<uids.length; i++){
								if(uids[i].length()>0){
									pstmt.setInt(1, gid);
									pstmt.setInt(2, Integer.valueOf(uids[i]));
									pstmt.setTimestamp(3, time);
									pstmt.addBatch();
								}
							}*/
							PreparedStatement pstmt = conn.prepareStatement("insert ignore into msg(title,time,sender_id,receiver_id,content) values(?,?,?,?,?)");
							PreparedStatement psys = conn.prepareStatement("insert ignore into msg(title,time,sender_id,receiver_id,content) values(?,?,?,?,?)");
							ArrayList<String> names = new ArrayList<String>();
							pstmt.setString(1, title);
							pstmt.setTimestamp(2, time);
							pstmt.setInt(3, Integer.parseInt(client_uid));
							pstmt.setInt(4, admin_uid);
							pstmt.setString(5, content);
//							pstmt.addBatch();
							pstmt.execute();
									
							MessageCache.getInstance().updateMessages(admin_uid);//=============
//							pstmt.executeBatch();
//							pstmt.clearBatch();
							psys.setString(1, "Apply Send Successfully");
							psys.setTimestamp(2, time);
							psys.setInt(3, 0);//SystemId=0
							psys.setInt(4, Integer.parseInt(client_uid));
							psys.setString(5, "&nbsp;&nbsp;&nbsp;&nbsp;Dear user,<br/>&nbsp;&nbsp;&nbsp;&nbsp;Your appliment have been sent to their message box successfully. Please wait patiently for their feed back.");
							psys.executeUpdate();
							psys.close();
							pstmt.close();
							conn.close();
							result="Apply message have sent to the administrator,\nplease wait for their acceptence";
							MessageCache.getInstance().updateMessages(Integer.parseInt(client_uid));
						}
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
//		System.out.println("validate:"+result);
		response.getWriter().print(result);
	}

}
